package cn.com.headfree.adjustment.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.adjustment.service.IAdjustMentService;
import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.TPersonYearPoint;
import cn.com.headfree.entity.TPointSetOver;
import cn.com.headfree.entity.TRecordOptLog;
import cn.com.headfree.entity.TSalaryInfo;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.recordlog.service.IRecordLogService;

/**
 * 积分调整
 */
@Controller
@RequestMapping(value = "/adjustment", produces = "application/json;charset=UTF-8")
public class AdjustMentController extends ExBaseController {
	private static final Logger LOG = LogManager.getLogger(AdjustMentController.class);

	@Autowired
	private IAdjustMentService adjustMentService;

	@Autowired
	private IRecordLogService recordLogService;

	/**
	 * 分页查询-->积分调整
	 */
	@RequestMapping("/getAdjustMentPage")
	@ResponseBody
	public ResultData getAdjustMentPage(Page<TPersonYearPoint> page,@RequestBody TPersonYearPoint tPersonYearPoint) {
		ResultData result = new ResultData();
		try {
			adjustMentService.getAdjustMentPage(page, tPersonYearPoint);
			result.setSuccess(true);
			result.setData(page);
			LOG.info("分页查询积分管理成功");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("分页查询积分管理失败！");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * “积分调整结束”前置接口
	 * @param baseOrgId
	 * @param year
	 * @return  返回0，表示积分调整已结束，1表示未结束
	 */
	public int preEndPoint(String baseOrgId,int year) {
		ResultData rs = new ResultData();
		try {
			TPointSetOver t=adjustMentService.preEndPoint(baseOrgId,year);
			if(t!=null) {
				return 0;
			}else {
				return 1;
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("积分调整结束失败！");
			e.printStackTrace();
		}
		return 0;
	}


	/**
	 *
	 * @param year
	 * @return
	 */
	@RequestMapping("/preEditPoint")
	@ResponseBody
	public ResultData preEditPoint(HttpServletRequest request,int year) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			TPointSetOver t=adjustMentService.preEndPoint(user.getBaseOrgId(),year);
			if(t!=null) {
				rs.setSuccess(false);
				rs.setErrorMsg("当年年度积分调整已结束，不允许再编辑！");
			}
			return rs;
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("积分编辑前置接口执行失败！");
			e.printStackTrace();
		}
		return rs;
	}


	/**
	 * “积分调整结束” 接口
	 * @param request
	 * @param response
	 * @param year
	 * @return
	 */
	@RequestMapping("/endPoint")
	public ResultData endPoint(HttpServletRequest request, HttpServletResponse response, int year) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			int flag=this.preEndPoint(user.getBaseOrgId(), year);
			if(flag==1) {
				//查看是否有待审核数据
				List<TSalaryInfo> data=adjustMentService.getDaiSalayInfo(year,user.getBaseOrgId(),"0");
				if(data!=null&&data.size()>0) {
					rs.setSuccess(false);
					rs.setErrorMsg("当前年度存在待审核数据，请先审核完毕！");
					return rs;
				}
				adjustMentService.endPoint(user,year);
				//获取所有的积分信息，重新赋分值
//				TPersonYearPoint t=new TPersonYearPoint();
//				t.setOrgId(user.getBaseOrgId());
//				t.setYear(year);
//				List<TPersonYearPoint> list = adjustMentService.getAdjustMentList(t, null);
//				for(TPersonYearPoint tp:list) {
//					if(tp.getLastYearPoint()+tp.getYearPoint()+tp.getTrimPoint()>=4) {
//						tp.setUsePoint(4.0);
//						double p=tp.getRemainPoint()-4;
//						tp.setRemainPoint(p>=0?p:0);
//						tp.setUseReason("薪档调整");
//						adjustMentService.updateTPersonYearPoint(tp);
//						//修改个人积分明细表的调整后合计字段
//						adjustMentService.editPointDetail(user.getFax(),year,p);
//					}
//				}
				LOG.info("积分调整结束成功！");
				rs.setData("积分调整结束成功！");
				return rs;
			}else {
				rs.setSuccess(false);
				rs.setErrorMsg("当前年度积分调整已经结束！");
				return rs;
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("积分调整结束失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 薪档编辑
	 * @param request
	 * @param id
	 * @param oldTrimPoint 原始积分
	 * @param trimPoint 调整后积分
	 * @param trimReason 调整原因
	 * @param remainPoint 剩余积分
	 * @param year 年度
	 * @return
	 */
	@RequestMapping("/editPoint")
	@ResponseBody
	public ResultData editPoint(HttpServletRequest request,String id, Double oldTrimPoint,Double trimPoint, String trimReason,Double remainPoint,String erpNo,int year,String salaryGrade) {
		ResultData result = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			adjustMentService.editPoint(id, trimPoint, trimReason,remainPoint,salaryGrade);
			//修改个人积分明细表的调整后合计字段
			adjustMentService.editPointDetail(erpNo,year,remainPoint,salaryGrade);
			//日志
		    TRecordOptLog log = new TRecordOptLog();
		    log.setCurrentRecordId(id);
		    log.setRecordId(id);
		    log.setOptType("2");
		    log.setOptContent(user.getName()+"修改了积分，由"+oldTrimPoint+"分改为了"+trimPoint+"分，原因:"+trimReason);
		    recordLogService.save(user,log);
			result.setSuccess(true);
			result.setData("积分编辑成功！");
			LOG.info("积分编辑成功！");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("积分编辑失败！");
			e.printStackTrace();
		}
		return result;
	}


	/**
	 * 导出
	 * @param req
	 * @param response
	 * @param tPersonYearPoint
	 * @param ids
	 */
	@RequestMapping("/exportFile")
	@ResponseBody
	public void exportFile(HttpServletRequest req, HttpServletResponse response,TPersonYearPoint tPersonYearPoint,
			String ids) {
		if (!StringUtil.isNullOrEmpty(ids)) {
			ids = spiltStr(ids);
		}
		System.out.println("开始时间:" + Calendar.getInstance().getTimeInMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<TPersonYearPoint> list = adjustMentService.getAdjustMentList(tPersonYearPoint, ids);
		System.out.println("结束时间:" + Calendar.getInstance().getTimeInMillis());
		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		SXSSFSheet sheet = wb.createSheet("积分管理列表");
		SXSSFRow row = null;
		row = sheet.createRow(0);
		try {
			SXSSFCell R1C0 = row.createCell(0);
			SXSSFCell R1C1 = row.createCell(1);
			SXSSFCell R1C2 = row.createCell(2);
			SXSSFCell R1C3 = row.createCell(3);
			SXSSFCell R1C4 = row.createCell(4);
			SXSSFCell R1C5 = row.createCell(5);
			SXSSFCell R1C6 = row.createCell(6);
			SXSSFCell R1C7 = row.createCell(7);
			SXSSFCell R1C8 = row.createCell(8);
			SXSSFCell R1C9 = row.createCell(9);
			SXSSFCell R1C10 = row.createCell(10);
			SXSSFCell R1C11 = row.createCell(11);
			SXSSFCell R1C12 = row.createCell(12);
			SXSSFCell R1C13 = row.createCell(13);
			R1C0.setCellValue("序号");
			R1C1.setCellValue("所属部门");
			R1C2.setCellValue("ERP编号");
			R1C3.setCellValue("姓名");
			R1C4.setCellValue("年度");
			R1C5.setCellValue("上年度剩余积分");
			R1C6.setCellValue("本年度积分");
			R1C7.setCellValue("积分调整");
			R1C8.setCellValue("积分调整原因");
			R1C9.setCellValue("调整后本年度积分");
			R1C10.setCellValue("本年使用积分");
			R1C11.setCellValue("使用积分原因");
			R1C12.setCellValue("剩余积分");
			R1C13.setCellValue("执行岗级");
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					row = sheet.createRow(i + 1);
					TPersonYearPoint result = list.get(i);
					row.createCell(0).setCellValue(i + 1);
					row.createCell(1).setCellValue(result.getDeptName());
					row.createCell(2).setCellValue(result.getErpNo());
					row.createCell(3).setCellValue(result.getUserName());
					row.createCell(4).setCellValue(result.getYear());
					row.createCell(5).setCellValue(result.getLastYearPoint());
					row.createCell(6).setCellValue(result.getYearPoint());
					row.createCell(7).setCellValue(result.getTrimPoint());
					row.createCell(8).setCellValue(result.getTrimReason());
					row.createCell(9).setCellValue(result.getTrimYearPoint());
					row.createCell(10).setCellValue(result.getUsePoint());
					row.createCell(11).setCellValue(result.getUseReason());
					row.createCell(12).setCellValue(result.getRemainPoint());
					row.createCell(13).setCellValue(result.getSalaryGrade());
				}
				sheet.trackAllColumnsForAutoSizing();
				sheet.autoSizeColumn(0);
				sheet.setColumnWidth(0, sheet.getColumnWidth(0) * 10 / 7);
				sheet.autoSizeColumn(1);
				sheet.setColumnWidth(1, sheet.getColumnWidth(1) * 10 / 6);
				sheet.autoSizeColumn(2);
				sheet.setColumnWidth(2, sheet.getColumnWidth(2) * 10 / 6);
				sheet.autoSizeColumn(3);
				sheet.setColumnWidth(3, sheet.getColumnWidth(3) * 10 / 4);
				sheet.autoSizeColumn(4);
				sheet.setColumnWidth(4, sheet.getColumnWidth(4) * 10 / 6);
				sheet.autoSizeColumn(5);
				sheet.setColumnWidth(5, sheet.getColumnWidth(5) * 10 / 6);
				sheet.autoSizeColumn(6);
				sheet.setColumnWidth(6, sheet.getColumnWidth(6) * 10 / 6);
				sheet.autoSizeColumn(7);
				sheet.setColumnWidth(7, sheet.getColumnWidth(7) * 10 / 5);
				sheet.autoSizeColumn(8);
				sheet.setColumnWidth(8, sheet.getColumnWidth(8) * 10 / 6);
				sheet.autoSizeColumn(9);
				sheet.setColumnWidth(9, sheet.getColumnWidth(9) * 10 / 5);
				sheet.autoSizeColumn(10);
				sheet.setColumnWidth(10, sheet.getColumnWidth(10) * 10 / 5);
				sheet.autoSizeColumn(11);
				sheet.setColumnWidth(11, sheet.getColumnWidth(11) * 10 / 5);
				sheet.autoSizeColumn(12);
				sheet.setColumnWidth(12, sheet.getColumnWidth(12) * 10 / 6);
				sheet.autoSizeColumn(13);
				sheet.setColumnWidth(13, sheet.getColumnWidth(13) * 10 / 5);
			}
			OutputStream os = response.getOutputStream();
			String nameString = "积分管理列表.xlsx";
			final String userAgent = req.getHeader("USER-AGENT");
			String finalFileName = null;
			if (userAgent.contains("Mozilla") || userAgent.contains("Chrome")) {// google,火狐浏览器
				finalFileName = new String(nameString.getBytes(), "ISO8859-1");
			} else {
				finalFileName = URLEncoder.encode(nameString, "UTF8");// 其他浏览器
			}
			response.setHeader("Content-disposition", "attachment;filename=\"" + finalFileName + "\"");// 默认Excel名称
			// 设置响应的编码
			response.setContentType("application/vnd.ms-excel;charset=utf-8");//
			// 下面三行是关键代码，处理乱码问题
			response.setCharacterEncoding("utf-8");
			wb.write(os);
			os.flush();
			os.close();
			LOG.info("下载成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static String spiltStr(String str) {
		StringBuffer sb = new StringBuffer();
		String[] temp = str.split(",");
		for (int i = 0; i < temp.length; i++) {
			if (!"".equals(temp[i]) && temp[i] != null)
				sb.append("'" + temp[i] + "',");
		}
		String result = sb.toString();
		String tp = result.substring(result.length() - 1, result.length());
		if (",".equals(tp))
			return result.substring(0, result.length() - 1);
		else
			return result;
	}

}
